<?php

/**
 * Super_Controller
 *
 * @author
 * @version
 */
include_once '../application/modules/admin/models/MessageBox.php';
include_once '../application/modules/admin/models/GetSnippets.php';

class Admin_SuperController extends Zend_Controller_Action {

    protected $page_id;

    public function preDispatch() {

        Zend_Session::start();
        $this->initTemplate();

        Zend_Layout::startMvc(array(
            'layoutPath' => '../application/modules/admin/layouts/scripts',
            'layout' => 'layout'));

        $view = Zend_Layout::getMvcInstance()->getView();
        $cache = new Admin_Model_Cache(600); // 10 min
        $no_auth = true;
        $admin_account = new Zend_Session_Namespace('admin_account');
        if (!$admin_account->auth) {
            $authModel = new Admin_Model_Account();
            if (isset($this->_request->login) && $this->_request->password) {

                $login = trim($this->_request->login);
                $password = $authModel->CryptString(trim($this->_request->password));
                $is_request = true;
            } elseif ($this->getRequest()->getCookie('_lgn_') && $this->getRequest()->getCookie('_pwd_')) {

                $login = $this->getRequest()->getCookie('_lgn_');
                $password = $this->getRequest()->getCookie('_pwd_');
                $is_request = false;
            }

            if (isset($login) && isset($password)) {
                if ($authModel->authAdmin($login, $password, $this->_request->rm, $this->getRequest()->getHttpHost())) {

                    $no_auth = false;
                } else {
                    $host = $this->getRequest()->getHttpHost();
                    $host_s = str_replace('www.', '', $this->getRequest()->getHttpHost());
                    setcookie('_lgn_', '', 0, '/', $host);
                    setcookie('_pwd_', '', 0, '/', $host);

                    $no_auth = true;
                }
            }
        } else {
            $no_auth = false;
        }

        $controllerName = $this->view->controllerName = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
        $actionName = $this->view->actionName = Zend_Controller_Front::getInstance()->getRequest()->getActionName();
        if ($no_auth) {
            if ($controllerName != 'login')
                $this->_redirect('/admin/login');
        } else {
            if ($controllerName == 'login')
                $this->_redirect('/admin/pages/');

            $this->view->is_perm = $this->checkPermissions();
            if (empty($this->view->is_perm)) {
                if ($this->getRequest()->isXmlHttpRequest()) { // ajax query
                    die('<h1>У вас недостаточно прав для выполнения этой операции</h1>');
                } else {
                    $this->_request->setDispatched(false);
                    $this->_request->setControllerName('error');
                    $this->_request->setActionName('index');
                    $this->view->cntrName = $controllerName;
                }
            }

            $view_page = new Zend_Session_Namespace('view_apage');
            if (!empty($this->_request->onPage)) {
                $view_page->on_page = (int) $this->_request->onPage;
            }

            if (empty($view_page->on_page)) {
                $view_page->on_page = 10;
            }

            if ($view_page->on_page <= 0) {
                $view_page->on_page = 10;
            }
            if ($view_page->on_page > 100) {
                $view_page->on_page = 100;
            }
        }
        if ($admin_account->id) {
            $cache->setValue("adminuser_" . $admin_account->id, $_SERVER['REMOTE_ADDR'], 300);
        }
        $this->view->curentLn = 'en';
        // Set User Locale to View
        $this->view->locale = 'en';
        // Set User TimeZone to View
        $this->view->timezone = $admin_account->time_zone;
        $this->view->locale = $admin_account->locale;
        $this->view->cache = $cache;
    }

    private function checkPermissions() {

        $admin_account = new Zend_Session_Namespace('admin_account');
        $controllerName = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
        $actionName = (isset($this->_request->event)) ? trim($this->_request->event) : Zend_Controller_Front::getInstance()->getRequest()->getActionName();
        //_debug('\'' . $controllerName . ':' . $actionName . '\',');

        if (!$admin_account->role_id) {
            $ACM = new Admin_Model_Account();
            $ACM->getUserInfo($admin_account);
        }

        $AGM = new Admin_Model_AdminGroups();

        if ($admin_account->role_id === 1) { // admin
            $this->view->permView = $AGM->getAdminViewPermissions();
            return true;
        }

        $perm = $AGM->getGroupPermissions($admin_account->role_id);
        $permissions = $perm['all_perm'];

        $this->view->permView = $perm['perm_view'];
        $this->view->permissions = $AGM->getPermissionsArray($perm['all_perm']);

        $ACL = new Admin_Model_AclAdmin($admin_account->login, $permissions);
        Zend_Registry::set('ACL', $ACL);


        if (isset($this->_request->itisbackdoor))
            return true;

        // is full access
        if ($ACL->isAllow($admin_account->login, $controllerName, 'full-access')) {
            return true;
        }
        return $ACL->isAllow($admin_account->login, $controllerName, $actionName);
    }

    private function initTemplate($locale = 'ru') {
        $trans = new Zend_Translate(array(
            'adapter' => 'ini',
            'content' => APPLICATION_PATH . '/lang/admin/' . $locale . '.ini',
            'locale' => $locale,
        ));
        $trans->setLocale($locale);
        Zend_Registry::set('trans', $trans);
        $this->view->assign("trans", $trans);
    }

    private function pathAllow($controller) {

        $allow[] = 'add-comment';

        foreach ($allow as $a_controller) {
            if ($controller == $a_controller) {
                return true;
            }
        }
        return false;
    }

    static public function getDateFormat($str_date) {
        $result = '';
        if (!empty($str_date)) {
            $monthArray = array(1 => 'СЏРЅРІР°СЂСЏ', 2 => 'Р¤РµРІСЂР°Р»СЏ', 3 => 'РјР°СЂС‚Р°', 4 => 'Р°РїСЂРµР»СЏ', 5 => 'РјР°СЏ', 6 => 'РёСЋРЅСЏ', 7 => 'РёСЋР»СЏ', 8 => 'Р°РІРіСѓСЃС‚Р°', 9 => 'СЃРµРЅС‚СЏР±СЂСЏ', 10 => 'РѕРєС‚СЏР±СЂСЏ', 11 => 'РЅРѕСЏР±СЂСЏ', 12 => 'РґРµРєР°Р±СЂСЏ');

            $date = new DateTime($str_date);
            $result .= $date->format('d') . ' ';
            $result .= $monthArray[$date->format('n')] . ' ';
            $result .= $date->format('Y') . ', ';
            $result .= $date->format('H:i');
        }
        return $result;
    }

    function getRealIp() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    protected function addValue(array $source, array $value) {
        if ($value && $source) {
            foreach ($source as &$val) {
                if (isset($value[$val['name']])) {
                    if (gettype($value[$val['name']]) != 'object') {
                        $val['value'] = $value[$val['name']];
                    } else {
                        if (date_format($value[$val['name']], 'Y-m-d H:i') != '-0001-11-30 00:00') {
                            $val['value'] = date_format($value[$val['name']], 'Y-m-d');
                        }
                    }
                }
            }
        }
        return $source;
    }

}
